'use client';

import { createStore, Provider } from 'jotai';
import { appThemeAtom, userAtom, storageSystemOptionsAtom } from 'src/model';
import type { AppTheme, StorageSystemOption, User } from 'src/model';

export interface JotaiProviderProps {
  initialValues?: {
    appTheme?: AppTheme;
    user?: User;
    storageSystemOptions?: StorageSystemOption[];
  };
  children: React.ReactNode;
}

export function JotaiProvider(props: JotaiProviderProps) {
  const { initialValues, children } = props;

  const { appTheme, user, storageSystemOptions } = initialValues || {};

  const initialStore = createStore();

  if (appTheme) {
    initialStore.set(appThemeAtom, appTheme);
  }
  if (user) {
    initialStore.set(userAtom, user);
  }
  if (storageSystemOptions) {
    initialStore.set(storageSystemOptionsAtom, storageSystemOptions);
  }

  return <Provider store={initialStore}>{children}</Provider>;
}
